﻿using Hzt_WebApi.service;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebHzt_Api.Models;
using WebHzt_Api.Models.Database;

namespace Hzt_WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : Controller
    {
        private readonly Hzt_WebApiContext _db;
        private readonly IJWTService _jwtService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtService"></param>
        public readonly IUserService _userService;


        public UserController(Hzt_WebApiContext db, IJWTService jwtservice, IUserService userService)
        {
            _db = db;
            _jwtService = jwtservice;
            _userService = userService;
        }
        [HttpPost]
        public string CreateToken(string Password, string Email, int UserId)
        {
            return _jwtService.CreateToken(Password, Email, UserId);
        }
        /// <summary>
        /// 用户模块：注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {

            //判断手机号码是否重复 拿这个手机号码 去数据库查 有没有存在
            if (_db.Users.Any(x => x.Email == request.Email))
                return "账号已存在";
            _db.Users.Add(new User
            {
                Password = request.Password,
                Email = request.Email,
                CareTime = DateTime.Now
            });
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }
        /// <summary>
        /// 用户模块:登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(string email, string password)
        {
            //第一步 从数据库查询用户为username的用户
            //如果不存在用户就不存在
            //如果存在 判断查询出来的用户密码是不是与password相等
            //如果不相等 返回密码不正确
            //如果相等
            //创建Token返回token给前端
            //var user = _db.Users.FirstOrDefault(x => x.Email ==email);
            var user = _userService.GetUserByUserName(email);
            if (user == null)
            {
                return "用户不存在";
            }
            if (user.Password != password)
            {
                return "密码不正确";
            }
            return _jwtService.CreateToken(user.Password, user.Email, user.UserId);
        }
    }
}

